class UsersController < ApplicationController
  #skip_before_filter :authorize, :only => [:new, :edit, :create, :update]
  
  # GET /users
  # GET /users.xml
  def index
    @users = User.find(:all, :order => :name)
	@user = User.find(session[:user_id])
	if (@user.isAdmin?)
		respond_to do |format|
			format.html # index.html.erb
			format.xml  { render :xml => @users }
		end
	else 
		flash[:notice] = "Please log in [Administrators only]" 
		redirect_to :controller => 'admin', :action => 'login'
	end
  end

  # GET /users/1
  # GET /users/1.xml
  def show
   @loggedin_user = User.find(session[:user_id]) if session[:user_id]
   
   if (@user = User.find(params[:id]) && @loggedin_user)
		if (@loggedin_user.isAdmin? || @loggedin_user == @user)
			respond_to do |format|
				format.html # show.html.erb
				format.xml  { render :xml => @user }
			end
		else 
			flash[:notice] = "Please log in [Administrators only]" 
			redirect_to :controller => 'admin', :action => 'login'
		end
	else
		redirect_to :controller => 'store', :action => 'index'
	end
	
  end

  # GET /users/new
  # GET /users/new.xml
  def new
    @loggedin_user = User.find(session[:user_id]) if session[:user_id]
    @user = User.new
    @user.build_address # creates a new address object in the separate table, sets the foreign key to this user id, but is not saved yet. We do that upon submitting.
	
    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @user }
    end
  end

  # GET /users/1/edit
  def edit
    
    @user = User.find(params[:id])
    @loggedin_user = @user
    if @user.address.nil?
      @user.build_address # creates a new address object in the separate table, sets the foreign key to this user id, but is not saved yet.  We do that upon submitting.
    end
  end

  # POST /users
  # POST /users.xml
  def create
    @user = User.new(params[:user]) # the nested attributes of the address (foreign association) are also in here and get created appropriately


    respond_to do |format|
      if @user.save  # does this save the nested objects?  i.e address?
        flash[:notice] = "User #{@user.nickName} was successfully created."
#maybe add here, that new user is automatically logged in after registration!!	
		session[:user_id] = @user.id	
        format.html { redirect_to(:controller => 'store', :action => 'index') }
        format.xml  { render :xml => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  # PUT /users/1
  # PUT /users/1.xml
  def update
	@loggedin_user = User.find(session[:user_id]) if session[:user_id]
    
	if (@user = User.find(params[:id]) && @loggedin_user)
		if (@loggedin_user.isAdmin? || @loggedin_user == @user)

			Order.find(:all, :conditions => ['email = ?', @loggedin_user.email]).each do |o| 
				o.update_attributes({ :email => params[:user][:email] })
			end
		  respond_to do |format|
			if @user.update_attributes(params[:user])
			
			  flash[:notice] = "User #{@user.nickName} was successfully updated."
			  format.html { redirect_to(:action => 'show') }
			  format.xml  { head :ok }
		    else
			  format.html { render :action => "edit" }
			  format.xml  { render :xml => @user.errors, :status => :unprocessable_entity }
		    end
		  end
	    end
	end
  end

  # DELETE /users/1
  # DELETE /users/1.xml
  def destroy
    @user = User.find(params[:id])
    # EXCEPTIONS!  begin and rescue are try and catch
    begin
      flash[:notice] = "User #{@user.name} deleted"
      @user.destroy # read explanation below.
    rescue Exception => e
      flash[:notice] = e.message
    end
    # ABOUT the line above.  What happens is this:  the destroy method gets called, which isn't finished until all of its callbacks also finish.  Because we've overwritten after_destroy, and after_destroy will raise an exception if you tried to delete the last record, the entire destroy method will 'undo' what it did up until that point.  So if we try this line of code above, and you try to delete the last user (administrator), you won't be allowed to.  If for whatever reason you have no administrator, you can create one using the script/console command.
    
    respond_to do |format|
      format.html { redirect_to(users_url) }
      format.xml  { head :ok }
    end
  end
  
  def authorize
   #override application controller, so new user can register themselves
  end
  
 
end
